package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.exception.ServiceException;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.dto.BrandAddNewDTO;
import cn.tedu.csmall.product.pojo.dto.BrandUpdateDTO;
import cn.tedu.csmall.product.pojo.entity.Brand;
import cn.tedu.csmall.product.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.repo.BrandRedisRepository;
import cn.tedu.csmall.product.service.BrandService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理品牌业务的实现类
 *
 * @author Chen
 * @since 2023/2/7 18:38:38
 */
@Slf4j
@Service
public class BrandServiceImpl implements BrandService {

    private final BrandMapper brandMapper;
    private final BrandCategoryMapper brandCategoryMapper;
    private final SpuMapper spuMapper;
    private final BrandRedisRepository brandRedisRepository;

    @Autowired
    public BrandServiceImpl(BrandMapper brandMapper, BrandCategoryMapper brandCategoryMapper, SpuMapper spuMapper, BrandRedisRepository brandRedisRepository) {
        log.debug("创建业务实现类对象：BrandServiceImpl");
        this.brandMapper = brandMapper;
        this.brandCategoryMapper = brandCategoryMapper;
        this.spuMapper = spuMapper;
        this.brandRedisRepository = brandRedisRepository;
    }

    @Override
    public void addNew(BrandAddNewDTO brandAddNewDTO) {
        log.debug("开始处理【添加品牌】的业务，参数：{}", brandAddNewDTO);
        // 检查品牌名称是否已经被占用
        String name = brandAddNewDTO.getName();
        int count = brandMapper.countByName(name);
        if (count > 0) {
            String message = "添加品牌失败，品牌名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewDTO, brand);
        log.debug("即将插入数据，参数：{}", brand);
        int rows = brandMapper.insert(brand);
        if (rows != 1) {
            String message = "添加相册失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据id删除品牌】的业务，参数：{}", id);
        // 检查有无关联数据(category/spu)
        {
            int count = brandCategoryMapper.countByBrand(id);
            if (count > 0) {
                String message = "删除品牌失败，该品牌存在关联的类别！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        {
            int count = spuMapper.countByBrand(id);
            if (count > 0) {
                String message = "删除品牌失败，该品牌存在关联的SPU！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        // 执行删除操作
        log.debug("即将执行删除品牌的操作，参数：{}", id);
        int rows = brandMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除品牌失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void updateInfoById(Long id, BrandUpdateDTO brandUpdateDTO) {
        log.debug("开始处理【根据id修改品牌详情】的业务，参数ID：{}，新数据：{}", id, brandUpdateDTO);
        {
            // 是否存在该id的数据
            BrandStandardVO brand = brandMapper.getStandardById(id);
            if (brand == null) {
                String message = "更新品牌详情失败，尝试访问的数据不存在！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
        }
        {
            // 是否存在非此id占用此名称的数据
            int count = brandMapper.countByNameAndNotId(id, brandUpdateDTO.getName());
            if (count > 0) {
                String message = "更新品牌详情失败，尝试访问的数据名称已经被其他数据占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        // 创建brand对象
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateDTO, brand);
        brand.setId(id);
        log.debug("即将执行修改数据，参数：{}", brand);
        // 执行修改操作
        int rows = brandMapper.update(brand);
        if (rows != 1) {
            String message = "修改品牌详情失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据id获取品牌详情】的业务，参数：{}", id);
//        BrandStandardVO brand = brandMapper.getStandardById(id);
        BrandStandardVO brand = brandRedisRepository.get(id);
        if (brand == null) {
            String message = "查询品牌详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("即将返回查询结果：{}", brand);
        return brand;
    }

    @Override
    public List<BrandListItemVO> list() {
        log.debug("开始处理【获取品牌列表】的业务，参数：无");
//        return brandMapper.list();
        return brandRedisRepository.list();
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public void rebuildCache() {
        log.debug("开始处理【重建缓存】的业务，无参数");
        brandRedisRepository.deleteAll();
        List<BrandListItemVO> list = brandMapper.list();
        brandRedisRepository.save(list);
        for (BrandListItemVO brandListItemVO : list) {
            Long brandId = brandListItemVO.getId();
            BrandStandardVO brandStandardVO = brandMapper.getStandardById(brandId);
            brandRedisRepository.save(brandStandardVO);
        }
    }

    private void updateEnableById(Long id, Integer enable) {
        String[] enableText = {"禁用", "启用"};
        log.debug("开始处理【{}品牌】的业务，ID：{}，目标状态：{}", enableText[enable], id, enable);
        BrandStandardVO queryResult = brandMapper.getStandardById(id);
        if (queryResult == null) {
            String message = enableText[enable] + "品牌失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (queryResult.getEnable().equals(enable)) {
            String message = enableText[enable] + "品牌失败，当前品牌已经处于" + enableText[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        // 准备执行更新
        Brand brand = new Brand();
        brand.setId(id);
        brand.setEnable(enable);
        log.debug("即将修改数据，参数：{}", brand);
        int rows = brandMapper.update(brand);
        if (rows != 1) {
            String message = enableText[enable] + "品牌失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

}
